//
//  EditPermissionGroupController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "EditPermissionGroupController.h"

#import "FormattingUtilities.h"
#import "GSSCommunicator.h"
#import "GSSGroups.h"

@implementation EditPermissionGroupController

@synthesize groups;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.dataSourceDictionary setObject:@"" forKey:@"group"];
    
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)];
	
	groupCtl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	
    GSSCommunicator *communicator = [GSSCommunicator defaultCommunicator];
	self.groups = communicator.groups;
    if (self.groups.isStale)
        [communicator updateMetaOfObject:self.groups];
    loadingView.hidden = !self.groups.isEmpty;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [self.groups addObserver:self forKeyPath:@"meta" options:0 context:NULL];
    [self.groups addObserver:self forKeyPath:@"error" options:0 context:NULL];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
    [self.groups removeObserver:self forKeyPath:@"meta"];
    [self.groups removeObserver:self forKeyPath:@"error"];
}

- (void)dealloc {
    [super dealloc];

	[groups release];
}

- (void)save:(id)sender {
    NSArray *items = self.groups.children;
	NSInteger row = [groupCtl selectedRowInComponent:0];
	if (row >= 0 && row < [items count])
		[self.dataSourceDictionary setObject:[items objectAtIndex:[groupCtl selectedRowInComponent:0]]
                                      forKey:@"group"];
	[super save:self];	
}

//MARK: -
//MARK: Controls and functions

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)anObject change:(NSDictionary *)change context:(void *)context {    
    if ([keyPath isEqualToString:@"meta"]) {
		[groupCtl reloadAllComponents];
        NSArray *items = self.groups.children;
		if ([items count] > 0) {
			((UILabel *)nameCtl).text = [items objectAtIndex:0];
		}        
		loadingView.hidden = YES;
    } else if ([keyPath isEqualToString:@"error"]) {
			UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:LocalizedString(@"Group error")
																message:LocalizedString(@"{Group communication error}")
															   delegate:nil
													  cancelButtonTitle:LocalizedString(@"OK")
													  otherButtonTitles:nil];
			[alertView show];
			[alertView release];
        return;        
    }
}

- (UILabel *)nameCtl {
	
	if (nameCtl == nil) {
		nameCtl = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 10.0, 290.0, 24.0)];
		((UILabel *)nameCtl).adjustsFontSizeToFitWidth = YES;
		((UILabel *)nameCtl).minimumFontSize = 9.0;
		((UILabel *)nameCtl).textColor = [UIColor colorWithRed:0.32 green:0.4 blue:0.57 alpha:1];
		((UILabel *)nameCtl).backgroundColor = [UIColor clearColor];
		((UILabel *)nameCtl).autoresizingMask = UIViewAutoresizingFlexibleWidth;
	}
	
	((UILabel *)nameCtl).text = [self.dataSourceDictionary objectForKey:@"group"];
	
	return nameCtl;
}

//MARK: -
//MARK: UIPickerView delegate and dataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSArray *items = self.groups.children;
	if (row >= 0 && row < [items count])
		((UILabel *)nameCtl).text = [items objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.groups.children count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.groups.children objectAtIndex:row];
}

@end